'use client';

import { useState, useEffect } from 'react';
import { useAuth } from '@/contexts/AuthContext';
import { useRouter } from 'next/navigation';
import BrandFilter from '@/components/BrandFilter';
import ConfigSelector from '@/components/ConfigSelector';
import CarMediaUpload from '@/components/CarMediaUpload';
import { CarMediaUpload as CarMediaUploadType, MediaType, MediaCategory } from '@/types';

interface Brand {
  brand: string;
  name: string;
  alphabet: string;
  country: string;
  hot: string;
  desc: string;
  story: string;
}


export default function NewCarPage() {
  const { user } = useAuth();
  const router = useRouter();
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [brands, setBrands] = useState<Brand[]>([]);
  const [selectedBrand, setSelectedBrand] = useState('');
  const [carType, setCarType] = useState<'new' | 'used'>('new');
  const [selectedConfigs, setSelectedConfigs] = useState<number[]>([]);
  const [isAuthorized, setIsAuthorized] = useState(false);
  const [exteriorMedia, setExteriorMedia] = useState<CarMediaUploadType[]>([]);
  const [interiorMedia, setInteriorMedia] = useState<CarMediaUploadType[]>([]);
  const [videoMedia, setVideoMedia] = useState<CarMediaUploadType[]>([]);

  useEffect(() => {
    // 动态导入品牌数据
    import('@/../public/brandData.js')
      .then((module) => {
        setBrands(module.default || []);
      })
      .catch((error) => {
        console.error('加载品牌数据失败:', error);
      });
  }, []);

  useEffect(() => {
    // 权限检查放在useEffect中，避免在渲染过程中调用router.push
    if (!user || user.role !== 'admin') {
      router.push('/login');
    } else {
      setIsAuthorized(true);
    }
  }, [user, router]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    // 验证必填字段
    if (!selectedBrand) {
      alert('请选择品牌');
      return;
    }
    
    if (exteriorMedia.length === 0) {
      alert('请至少上传一张外观图片');
      return;
    }
    
    // 检查所有媒体文件是否已上传完成
    const allMedia = [...exteriorMedia, ...interiorMedia, ...videoMedia];
    const unuploadedMedia = allMedia.filter(media => !media.url && !media.isUploading);
    
    if (unuploadedMedia.length > 0) {
      alert('请先上传所有选中的媒体文件');
      return;
    }
    
    const uploadingMedia = allMedia.filter(media => media.isUploading);
    if (uploadingMedia.length > 0) {
      alert('请等待文件上传完成');
      return;
    }
    
    setIsSubmitting(true);
    
    try {
      // 准备提交数据
      const formData = {
        brand: selectedBrand,
        carType,
        configs: selectedConfigs,
        exteriorMedia: exteriorMedia.filter(media => media.url).map(media => ({
          type: MediaType.IMAGE,
          category: MediaCategory.EXTERIOR,
          url: media.url
        })),
        interiorMedia: interiorMedia.filter(media => media.url).map(media => ({
          type: MediaType.IMAGE,
          category: MediaCategory.INTERIOR,
          url: media.url
        })),
        videoMedia: videoMedia.filter(media => media.url).map(media => ({
          type: MediaType.VIDEO,
          category: MediaCategory.EXTERIOR, // 视频默认归类为外观
          url: media.url
        }))
      };
      
      console.log('提交数据:', formData);
      
      // 模拟提交
      setTimeout(() => {
        alert('车辆添加成功！');
        router.push('/admin/cars');
      }, 1000);
      
    } catch (error) {
      console.error('提交失败:', error);
      alert('提交失败，请重试');
    } finally {
      setIsSubmitting(false);
    }
  };

  if (!isAuthorized) {
    return null;
  }

  return (
    <>
      <div className="mb-4 flex items-center gap-2">
        <h1 className="text-3xl font-bold text-gray-900">添加汽车</h1>
        <p className="text-gray-600">填写车辆详细信息</p>
      </div>

      <div className="bg-white rounded-lg shadow-sm border p-6">
        <form onSubmit={handleSubmit} className="space-y-6">
          {/* 新车/二手车切换按钮 */}
          <div className="mb-6">
            <label className="block text-sm font-medium text-gray-700 mb-3">
              车辆类型 *
            </label>
            <div className="flex space-x-4">
              <button
                type="button"
                onClick={() => setCarType('new')}
                className={`px-6 py-2 rounded-lg border font-medium transition-colors ${
                  carType === 'new'
                    ? 'bg-blue-600 text-white border-blue-600'
                    : 'bg-white text-gray-700 border-gray-300 hover:bg-gray-50'
                }`}
              >
              新车
              </button>
              <button
                type="button"
                onClick={() => setCarType('used')}
                className={`px-6 py-2 rounded-lg border font-medium transition-colors ${
                  carType === 'used'
                    ? 'bg-blue-600 text-white border-blue-600'
                    : 'bg-white text-gray-700 border-gray-300 hover:bg-gray-50'
                }`}
              >
                二手车
              </button>
            </div>
          </div>

          <div>

            {/* <div> */}
              <label className="block text-sm font-medium text-gray-700 mb-2">
                品牌 *
              </label>
              {selectedBrand && (
                <div className="mb-3 p-3 bg-blue-50 border border-blue-200 rounded-lg">
                  <div className="flex items-center gap-3">
                    <img 
                      src={`/car-logo/${selectedBrand}.png`}
                      alt={brands.find(b => b.brand === selectedBrand)?.name || ''}
                      className="w-10 h-10 object-contain"
                      onError={(e) => {
                        e.currentTarget.style.display = 'none';
                      }}
                    />
                    <div>
                      <div className="font-semibold text-gray-900">
                        {brands.find(b => b.brand === selectedBrand)?.name}
                      </div>
                      <div className="text-sm text-gray-600">
                        {selectedBrand}
                      </div>
                    </div>
                    <button
                      type="button"
                      onClick={() => setSelectedBrand('')}
                      className="ml-auto text-gray-400 hover:text-gray-600"
                    >
                      重新选择
                    </button>
                  </div>
                </div>
              )}
              
              {!selectedBrand && (
                <div className="border border-gray-300 rounded-lg p-4">
                  <BrandFilter
                    onBrandSelect={setSelectedBrand}
                    selectedBrand={selectedBrand}
                    showHotBrands={false}
                  />
                </div>
              )}
              
              {!selectedBrand && (
                <div className="mt-2 text-xs text-gray-500">
                  点击品牌卡片选择品牌
                </div>
              )}
            {/* </div> */}
          </div>
                      <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                车辆名称 *
              </label>
              <input
                type="text"
                required
                className="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
                placeholder="例如: Model S"
              />
            </div>

          {/* 新车和二手车共有的基本信息 */}
          <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                价格 (元) *
              </label>
              <input
                type="number"
                required
                min="0"
                className="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
                placeholder={carType === 'new' ? "280000" : "150000"}
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                年份 *
              </label>
              <input
                type="number"
                required
                min="1900"
                max="2025"
                className="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
                placeholder="2024"
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                级别 *
              </label>
              <select
                required
                className="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
              >
                <option value="">请选择级别</option>
                <option value="sedan">轿车</option>
                <option value="suv">SUV</option>
                <option value="mpv">MPV</option>
                <option value="coupe">跑车</option>
                <option value="hatchback">掀背车</option>
              </select>
            </div>
          </div>

          {/* 新车特有信息 */}
          {carType === 'new' && (
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  出厂日期 *
                </label>
                <input
                  type="date"
                  required
                  className="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  质保期限 (年)
                </label>
                <select className="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">
                  <option value="">请选择质保期限</option>
                  <option value="3">3年</option>
                  <option value="5">5年</option>
                  <option value="8">8年</option>
                  <option value="10">10年</option>
                </select>
              </div>
            </div>
          )}

          {/* 二手车特有信息 */}
          {carType === 'used' && (
            <div className="space-y-6">
              <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    里程 (公里) *
                  </label>
                  <input
                    type="number"
                    required
                    min="0"
                    className="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
                    placeholder="50000"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    上牌日期 *
                  </label>
                  <input
                    type="date"
                    required
                    className="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    过户次数
                  </label>
                  <input
                    type="number"
                    min="0"
                    className="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
                    placeholder="1"
                  />
                </div>
              </div>
              
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    车况评级 *
                  </label>
                  <select
                    required
                    className="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
                  >
                    <option value="">请选择车况评级</option>
                    <option value="excellent">优秀</option>
                    <option value="good">良好</option>
                    <option value="fair">一般</option>
                    <option value="poor">较差</option>
                  </select>
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    是否有事故
                  </label>
                  <select className="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500">
                    <option value="">请选择</option>
                    <option value="no">无事故</option>
                    <option value="minor">轻微事故</option>
                    <option value="major">重大事故</option>
                  </select>
                </div>
              </div>
              
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  维修保养记录
                </label>
                <textarea
                  rows={3}
                  className="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
                  placeholder="请输入维修保养历史记录..."
                />
              </div>
            </div>
          )}

          {/* 共有的其他信息 */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                燃料类型 *
              </label>
              <select
                required
                className="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
              >
                <option value="">请选择燃料类型</option>
                <option value="gasoline">汽油</option>
                <option value="electric">电动</option>
                <option value="hybrid">混动</option>
                <option value="diesel">柴油</option>
              </select>
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                变速箱类型 *
              </label>
              <select
                required
                className="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
              >
                <option value="">请选择变速箱</option>
                <option value="manual">手动</option>
                <option value="automatic">自动</option>
                <option value="cvt">CVT无级变速</option>
                <option value="dct">双离合</option>
              </select>
            </div>
          </div>



          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              所在地 *
            </label>
            <input
              type="text"
              required
              className="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
              placeholder="例如: 北京"
            />
          </div>

          {/* 配置选择 */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              车辆配置 (可选)
            </label>
            <div className="border border-gray-300 rounded-lg p-4">
              <ConfigSelector
                selectedConfigs={selectedConfigs}
                onConfigChange={setSelectedConfigs}
                maxSelections={8}
              />
            </div>
          </div>

          {/* 外观图片上传 */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              外观图片 *
            </label>
            <div className="text-xs text-gray-500 mb-3">
              上传车辆外观图片，支持JPG、PNG格式，单个文件最大50MB
            </div>
            <CarMediaUpload
              onMediaChange={setExteriorMedia}
              maxFiles={10}
            />
            {exteriorMedia.length === 0 && (
              <div className="mt-1 text-xs text-red-500">
                请至少上传一张外观图片
              </div>
            )}
          </div>

          {/* 内饰图片上传 */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              内饰图片
            </label>
            <div className="text-xs text-gray-500 mb-3">
              上传车辆内饰图片，支持JPG、PNG格式，单个文件最大50MB
            </div>
            <CarMediaUpload
              onMediaChange={setInteriorMedia}
              maxFiles={10}
            />
          </div>

          {/* 视频上传 */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              视频
            </label>
            <div className="text-xs text-gray-500 mb-3">
              上传车辆相关视频，支持MP4格式，单个文件最大50MB
            </div>
            <CarMediaUpload
              onMediaChange={setVideoMedia}
              maxFiles={5}
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              车辆描述
            </label>
            <textarea
              rows={4}
              className="w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
              placeholder="请输入车辆详细描述..."
            />
          </div>

          <div className="flex justify-end space-x-4 pt-6">
            <button
              type="button"
              onClick={() => router.back()}
              className="px-6 py-2 text-gray-600 border border-gray-300 rounded-lg hover:bg-gray-50"
            >
              取消
            </button>
            <button
              type="submit"
              disabled={isSubmitting}
              className="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50"
            >
              {isSubmitting ? '提交中...' : '添加车辆'}
            </button>
          </div>
        </form>
      </div>
    </>
  );
}